package com.songcan.gateway.converter;

import com.songcan.gateway.vo.YfUsernamePasswordAuthenticationToken;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.function.Function;

@Deprecated
public class BearerAuthenticationConverter implements Function<ServerWebExchange, Mono<Authentication>> {


    private RedisTemplate redisTemplate;

    public BearerAuthenticationConverter(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    @Deprecated
    @Override
    public Mono<Authentication> apply(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String authorization = request.getHeaders().getFirst("Authorization");
        if (authorization != null && authorization.toLowerCase().startsWith("bearer ")) {
            String token = authorization.length() <= "Bearer ".length() ? "" : authorization.substring("Bearer ".length(), authorization.length());
            RedisTokenStore redisTokenStore = new RedisTokenStore(redisTemplate.getConnectionFactory());
            OAuth2Authentication auth2AccessToken = redisTokenStore.readAuthentication(token);
            if(Objects.isNull(auth2AccessToken)){
                return  Mono.empty();
            }
            return  Mono.just(new YfUsernamePasswordAuthenticationToken(auth2AccessToken.getPrincipal(),auth2AccessToken.getCredentials(),token));
        } else {
            return Mono.empty();
        }
    }
}
